package com.hc.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hc.api.model.PageCountModel;
import com.hc.api.model.UrlCountModel;
import com.hc.api.model.UrlStateCountModel;
import com.hc.api.utils.ApiUtil;
import com.hc.comm.base.BaseController;
import com.hc.comm.dto.AppManagerDTO;
import com.hc.comm.dto.AppMonitorDTO;
import com.hc.comm.model.ResultModel;
import com.hc.comm.utils.ExceptionUtils;
import com.hc.comm.utils.JsonUtils;
import com.hc.comm.utils.StringUtil;
import com.hc.service.model.AppManagerModel;
import com.hc.service.model.AppMonitorModel;
import com.hc.service.service.IAppManagerService;
import com.hc.service.service.IAppMonitorService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@Scope("prototype")
@RequestMapping("/" + ApiUtil.ApiVersion.V1 + "/app/")
public class AppManagerController extends BaseController {

    @Resource(name = "appManagerService")
    private IAppManagerService appManagerService;


    @Resource(name = "appMonitorService")
    private IAppMonitorService appMonitorService;

    @RequestMapping("index")
    public String index() throws Exception {

        return "api";
    }


    @RequestMapping("test")
    public void test() throws Exception {
        AppManagerDTO dto = new AppManagerDTO();
        dto.setToken("xmu_123456");
        AppManagerModel model = appManagerService.getOne(dto);
        Map<String, AppManagerModel> resultMap = new HashMap<String, AppManagerModel>();
        resultMap.put("appInfo", model);

        writeToJson(resultMap);
    }

    @ResponseBody
    @RequestMapping("appInfo")
    public ResultModel appInfo(@ModelAttribute AppManagerDTO dto) throws Exception {
        if (dto == null || !StringUtil.isNotEmpty(dto.getToken())) {
            ExceptionUtils.throwBaseException("参数异常");
        }

        AppManagerModel model = appManagerService.getOne(dto);

        Map<String, AppManagerModel> resultMap = new HashMap<String, AppManagerModel>();
        resultMap.put("appInfo", model);

        return JsonUtils.toResult(resultMap);
    }

    /**
     * data 客户端数据jsonArray
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("accessAppInfo")
    public void saveAppInfo() throws Exception {
        String data = request.getParameter("data");

        System.out.println("请求参数:" + data);
        if (StringUtil.isEmpty(data)) {
            // ExceptionUtils.throwBaseException("参数异常");
            JsonUtils.toErrorResult(request, response, "参数异常!");
            return;
        }

        List<AppMonitorModel> appMonitorModelList = JSON.parseArray(data, AppMonitorModel.class);
        int size = appMonitorModelList.size();
        if (appMonitorModelList == null || appMonitorModelList.isEmpty()) {
            JsonUtils.toErrorResult(request, response, "参数异常");
            ExceptionUtils.throwBaseException("操作失败!");
            return;
        }
        List<AppMonitorModel> newModelList = new ArrayList<>();
        for (AppMonitorModel model : appMonitorModelList) {
            if (StringUtil.isEmpty(model.getIp())) {
                model.setIp(getRemoteHost(request));
            }
            if (model.getStayPageTime() > 0 && String.valueOf(model.getStayPageTime()).length() > 10) {
                model.setStayPageTime(model.getStayPageTime() / 1000);
            }
            if (model.getIntoPageTime() > 0 && String.valueOf(model.getIntoPageTime()).length() > 10) {
                model.setIntoPageTime(model.getIntoPageTime() / 1000);
            }

            if (model.getOutPageTime() > 0 && String.valueOf(model.getOutPageTime()).length() > 10) {
                model.setOutPageTime(model.getOutPageTime() / 1000);
            }

            if (model.getInfoTime() > 0 && String.valueOf(model.getInfoTime()).length() > 10) {
                model.setInfoTime(model.getInfoTime() / 1000);
            }
            model.setCreateTime(System.currentTimeMillis() / 1000);
            newModelList.add(appMonitorService.insert(model));
        }
        if (size == newModelList.size()) {
            JsonUtils.toSuccessResult(request, response, "ok");
        } else {
            // ExceptionUtils.throwBaseException("操作失败!");
            JsonUtils.toErrorResult(request, response, "操作失败!");
        }


    }

    public String getRemoteHost(javax.servlet.http.HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * timeLines  加载时间
     * stayTimes 停留时间
     * platform 平台1 安卓，2ios
     * startData //开始日期
     * endData //节点日期
     *
     * @param appMonitorDTO
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("getPageLoadeTime")
    public void getPageLoadTime(@ModelAttribute AppMonitorDTO appMonitorDTO) throws Exception {

        if (appMonitorDTO == null || StringUtil.isEmpty(appMonitorDTO.getCurrentPage())) {
            JsonUtils.toErrorResult(request, response, "参数错误!");
            return;
        }
        System.out.println("page:" + appMonitorDTO.getCurrentPage());
        List appMonitorModelList = appMonitorService.getList(appMonitorDTO);
        if (appMonitorModelList == null) {
            JsonUtils.toErrorResult(request, response, "没有该页面!");
            return;
        }
        String platform = request.getParameter("platform");
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }

        //获取的时间分割参数
        String[] loadTimes = request.getParameterValues("timeLines");
        String[] stayTimes = request.getParameterValues("stayTimes");
        String statrData = request.getParameter("startData");
        String endData = request.getParameter("endData");
        if (!StringUtil.isEmpty(statrData) && !StringUtil.isNumeric(statrData)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        if (!StringUtil.isEmpty(endData) && !StringUtil.isNumeric(endData)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        appMonitorDTO.setOrderBy("load_time");
        StringBuilder loadTimenums = new StringBuilder();
        StringBuilder stayTimenums = new StringBuilder();
        if (loadTimes != null && loadTimes.length > 0) {
            if (!"0".equals(loadTimes[0])) {
                int num = appMonitorService.getLoadTimeCount(appMonitorDTO.getCurrentPage(),
                        "0", loadTimes[0], platform, statrData, endData);
                loadTimenums.append(num);
                loadTimenums.append(",");
            }
            for (int i = 0; i < loadTimes.length; i++) {
                if (i < loadTimes.length - 1) {
                    int num = appMonitorService.getLoadTimeCount(appMonitorDTO.getCurrentPage(),
                            loadTimes[i], loadTimes[i + 1], platform, statrData, endData);
                    loadTimenums.append(num);
                    loadTimenums.append(",");
                } else if (i == loadTimes.length - 1) {
                    int num = appMonitorService.getLoadTimeCount(appMonitorDTO.getCurrentPage(),
                            loadTimes[i], null, platform, statrData, endData);
                    loadTimenums.append(num);
                }
            }
        }
        if (stayTimes != null && stayTimes.length > 0) {
            if (!"0".equals(stayTimes[0])) {
                int num = appMonitorService.getStayTimeCount(appMonitorDTO.getCurrentPage(),
                        "0", stayTimes[0], platform, statrData, endData);
                stayTimenums.append(num);
                stayTimenums.append(",");
            }
            for (int i = 0; i < stayTimes.length; i++) {
                if (i < stayTimes.length - 1) {
                    int num = appMonitorService.getStayTimeCount(appMonitorDTO.getCurrentPage(),
                            stayTimes[i], stayTimes[i + 1], platform, statrData, endData);
                    stayTimenums.append(num);
                    stayTimenums.append(",");
                } else if (i == stayTimes.length - 1) {
                    int num = appMonitorService.getStayTimeCount(appMonitorDTO.getCurrentPage(),
                            stayTimes[i], null, platform, statrData, endData);
                    stayTimenums.append(num);
                }
            }
        }
        JSONObject json = new JSONObject();
        if (loadTimenums.length() > 0) {
            json.put("loadTime", loadTimenums);
        }
        if (stayTimenums.length() > 0) {
            json.put("stayTime", stayTimenums);
        }
        System.out.println("查询数据的条数：" + json);
        JsonUtils.toSuccessResult(request, response, json);
    }


    /**
     * 获取所有url的名称。访问次数
     * page 页数
     * pageSize 默认10条
     * platform 1:android,2:ios
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("url/all")
    public void getAllUrlNum() throws Exception {
        String page = request.getParameter("page");
        String pageSize = request.getParameter("pageSize");
        if (StringUtil.isEmpty(page) || !StringUtil.isNum(page)) {
            //默认只显示一页
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        String platform = request.getParameter("platform");
        if (StringUtil.isEmpty(pageSize) || !StringUtil.isNum(pageSize)) {
            pageSize = "10";
        }
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        int mPage = Integer.valueOf(page);
        int mSize = Integer.valueOf(pageSize);
        if (mPage < 1) {
            mPage = 1;
        }
        if (mSize > 100) {
            mSize = 100;
        }

        List<UrlCountModel> list = appMonitorService.getAllUrlNum(mSize * (mPage - 1), mPage * mSize, platform);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page", page);
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("urlNum", JSONArray.toJSON(list));
        JsonUtils.toSuccessResult(request, response, jsonObject, "netUrl", "num");
    }


    /***
     * 获取url的状态
     * netUrl  //完整的url名称必填
     *loadTimeLines //加载时间的时间分段  可选
     *netState //网络状态   可选
     *yjdUrlstate //医界贷接口状态 可选
     * requestTimeLines //请求的时间段
     * platform 1:android,2:ios
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("url/state")
    public void getUrlState(@ModelAttribute AppMonitorDTO appMonitorDTO) throws Exception {

        if (appMonitorDTO == null) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        //必须要url name
        if (StringUtil.isEmpty(appMonitorDTO.getNetUrl())) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        System.out.println("urlname:" + appMonitorDTO.getNetUrl());
        String[] loadTimes = request.getParameterValues("loadTimeLines");
        String[] requestTimeLines = request.getParameterValues("requestTimeLines");
        String reqStartTime = null;
        String reqEndTime = null;
        String platform = request.getParameter("platform");
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        if (requestTimeLines != null && requestTimeLines.length > 0) {
            reqStartTime = requestTimeLines[0];
            if (requestTimeLines.length > 1) {
                reqEndTime = requestTimeLines[1];
            }
        }
        System.out.println("reqStartTime:" + reqStartTime + "===reqEndTime:" + reqEndTime);
        List<UrlStateCountModel> urlStateCountModelList = new ArrayList<>();
        if (loadTimes != null && loadTimes.length > 0) {
            //设置了时间
            if (!"0".equals(loadTimes[0])) {
                List<UrlStateCountModel> urlStateCountModel = appMonitorService.getUrlState(appMonitorDTO.getNetUrl(),
                        appMonitorDTO.getNetState(), appMonitorDTO.getYjdUrlstate(), "0", loadTimes[0], reqStartTime, reqEndTime, platform);
                for (UrlStateCountModel model : urlStateCountModel) {
                    model.setLoadTimeLines("0");
                }
                urlStateCountModelList.addAll(urlStateCountModel);
            }
            for (int i = 0; i < loadTimes.length; i++) {
                if (i < loadTimes.length - 1) {
                    List<UrlStateCountModel> urlStateCountModel = appMonitorService.getUrlState(appMonitorDTO.getNetUrl(),
                            appMonitorDTO.getNetState(), appMonitorDTO.getYjdUrlstate(), loadTimes[i], loadTimes[i + 1],
                            reqStartTime, reqEndTime, platform);
                    for (UrlStateCountModel model : urlStateCountModel) {
                        model.setLoadTimeLines(loadTimes[i]);
                    }
                    urlStateCountModelList.addAll(urlStateCountModel);
                } else if (i == loadTimes.length - 1) {
                    List<UrlStateCountModel> urlStateCountModel = appMonitorService.getUrlState(appMonitorDTO.getNetUrl(),
                            appMonitorDTO.getNetState(), appMonitorDTO.getYjdUrlstate(), loadTimes[i], null,
                            reqStartTime, reqEndTime, platform);
                    for (UrlStateCountModel model : urlStateCountModel) {
                        model.setLoadTimeLines(loadTimes[i]);
                    }
                    urlStateCountModelList.addAll(urlStateCountModel);
                }
            }
        } else {
            //未设置时间段过滤的
            List<UrlStateCountModel> urlStateCountModel =
                    appMonitorService.getUrlState(appMonitorDTO.getNetUrl(),
                            appMonitorDTO.getNetState(), appMonitorDTO.getYjdUrlstate(), null, null,
                            reqStartTime, reqEndTime, platform);
            urlStateCountModelList.addAll(urlStateCountModel);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UrlStateCount", JSONArray.toJSON(urlStateCountModelList));
        JsonUtils.toSuccessResult(request, response, jsonObject);
    }

    /**
     * 获取所有访问页面的名称
     * platform 1:android,2:ios
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("page/allName")
    public void getAllPageName() throws Exception {
        String platform = request.getParameter("platform");
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        List<PageCountModel> appMonitorModelList = appMonitorService.getAllPageName(platform);
        JsonUtils.toSuccessResult(request, response, appMonitorModelList, "pageName", "showNum");
    }

    /**
     * 获取所有url状态
     * page //第几页
     * pagesize 每页的数量
     * platform 平台
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("url/allUrlState")
    public void getUrlStateCount() throws Exception {
        String page = request.getParameter("page");
        String pageSize = request.getParameter("pageSize");
        if (StringUtil.isEmpty(page) || !StringUtil.isNum(page)) {
            //默认只显示一页
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        String platform = request.getParameter("platform");
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        if (StringUtil.isEmpty(pageSize) || !StringUtil.isNum(pageSize)) {
            pageSize = "10";
        }
        int mPage = Integer.valueOf(page);
        int mSize = Integer.valueOf(pageSize);
        if (mPage < 1) {
            mPage = 1;
        }
        if (mSize > 100) {
            mSize = 100;
        }
        List<UrlCountModel> appMonitorModelList = appMonitorService.getUrlStateCount(mSize * (mPage - 1), mPage * mSize, platform);
        JsonUtils.toSuccessResult(request, response, appMonitorModelList, "netUrl", "num", "success", "fail", "unlogin", "avgTime");
    }

    /**
     * 获取所有页面的状态信息
     * page //第几页
     * pagesize 每页的数量
     * platform 平台
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("page/allPageState")
    public void getPageStateCount() throws Exception {
        String page = request.getParameter("page");
        String pageSize = request.getParameter("pageSize");
        if (StringUtil.isEmpty(page) || !StringUtil.isNum(page)) {
            //默认只显示一页
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        String platform = request.getParameter("platform");
        if (!StringUtil.isEmpty(platform) && !StringUtil.isNumeric(platform)) {
            JsonUtils.toErrorResult(request, response, "参数有误!");
            return;
        }
        if (StringUtil.isEmpty(pageSize) || !StringUtil.isNum(pageSize)) {
            pageSize = "10";
        }
        int mPage = Integer.valueOf(page);
        int mSize = Integer.valueOf(pageSize);
        if (mPage < 1) {
            mPage = 1;
        }
        if (mSize > 100) {
            mSize = 100;
        }
        List<PageCountModel> appMonitorModelList =
                appMonitorService.getPageStateCount(mSize * (mPage - 1), mPage * mSize, platform);
        JsonUtils.toSuccessResult(request, response, appMonitorModelList,
                "pageName", "appPageName", "showNum", "avgLoadTime", "avgStayPageTime");
    }
}
